package cn.edu.tju.elm.controller;

import cn.edu.tju.elm.model.Cart;
import cn.edu.tju.core.model.HttpResult;
import cn.edu.tju.core.model.ResultCodeEnum;
import cn.edu.tju.core.model.User;
import cn.edu.tju.core.security.service.UserService;
import cn.edu.tju.elm.service.CartService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api")
@Tag(name = "管理购物车", description = "对购物车内的商品增删改查")
public class CartController {
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private CartService cartService;

    // 1. 添加商品到购物车
    @PostMapping("/carts")
    @Operation(summary = "添加商品到购物车", description = "将商品添加到当前用户的购物车")
    public HttpResult<Cart> addCartItem(@RequestBody Cart cart) {
        try {
            // 获取当前登录用户
            User currentUser = userService.getUserWithAuthorities()
                    .orElseThrow(() -> new RuntimeException("用户未登录"));
            
            // 通过服务层添加购物车项
            Cart savedCart = cartService.addCartItem(cart, currentUser);
            return HttpResult.success(savedCart);
        } catch (IllegalArgumentException e) {
            return HttpResult.failure(ResultCodeEnum.PARAM_ERROR, e.getMessage());
        } catch (RuntimeException e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "添加购物车失败: " + e.getMessage());
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "系统错误: " + e.getMessage());
        }
    }

    // 2. 获取当前用户的购物车列表
    @GetMapping("/carts")
    @Operation(summary = "获取购物车列表", description = "获取当前用户购物车中的所有商品")
    public HttpResult<List<Cart>> getCartItems() {
        try {
            // 获取当前用户
            User currentUser = userService.getUserWithAuthorities()
                    .orElseThrow(() -> new RuntimeException("用户未登录"));
            
            // 通过服务层获取购物车项
            List<Cart> cartItems = cartService.getCartItems(currentUser);
            return HttpResult.success(cartItems);
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "获取购物车失败: " + e.getMessage());
        }
    }

    // 3. 获取指定购物车项详情
    @GetMapping("/carts/{id}")
    @Operation(summary = "获取购物车项详情", description = "根据ID获取购物车中特定商品的详细信息")
    public HttpResult<Cart> getCartItem(@PathVariable Long id) {
        try {
            // 获取当前用户
            User currentUser = userService.getUserWithAuthorities()
                    .orElseThrow(() -> new RuntimeException("用户未登录"));
            
            // 通过服务层获取购物车项
            Cart cartItem = cartService.getCartItem(id, currentUser);
            if (cartItem != null) {
                return HttpResult.success(cartItem);
            } else {
                return HttpResult.failure(ResultCodeEnum.NOT_FOUND, "购物车项不存在或无权访问");
            }
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "获取购物车项失败: " + e.getMessage());
        }
    }

    // 4. 更新购物车中商品数量
    @PutMapping("/carts/{id}")
    @Operation(summary = "更新购物车商品数量", description = "修改购物车中特定商品的数量")
    public HttpResult<Cart> updateCartItem(@PathVariable Long id, @RequestBody Cart cartDetails) {
        try {
            // 获取当前用户
            User currentUser = userService.getUserWithAuthorities()
                    .orElseThrow(() -> new RuntimeException("用户未登录"));
            
            // 通过服务层更新购物车项
            Cart updatedCartItem = cartService.updateCartItem(id, cartDetails, currentUser);
            if (updatedCartItem != null) {
                return HttpResult.success(updatedCartItem);
            } else {
                return HttpResult.failure(ResultCodeEnum.NOT_FOUND, "购物车项不存在或无权修改");
            }
        } catch (IllegalArgumentException e) {
            return HttpResult.failure(ResultCodeEnum.PARAM_ERROR, e.getMessage());
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "更新购物车项失败: " + e.getMessage());
        }
    }

    // 5. 从购物车中移除商品
    @DeleteMapping("/carts/{id}")
    @Operation(summary = "移除购物车商品", description = "从购物车中删除特定商品")
    public HttpResult<String> deleteCartItem(@PathVariable Long id) {
        try {
            // 获取当前用户
            User currentUser = userService.getUserWithAuthorities()
                    .orElseThrow(() -> new RuntimeException("用户未登录"));
            
            // 通过服务层删除购物车项
            cartService.deleteCartItem(id, currentUser);
            return HttpResult.success("购物车项删除成功");
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "删除购物车项失败: " + e.getMessage());
        }
    }

    // 6. 清空购物车
    @DeleteMapping("/carts")
    @Operation(summary = "清空购物车", description = "移除当前用户购物车中的所有商品")
    public HttpResult<String> clearCart() {
        try {
            // 获取当前用户
            User currentUser = userService.getUserWithAuthorities()
                    .orElseThrow(() -> new RuntimeException("用户未登录"));
            
            // 通过服务层清空购物车
            cartService.clearCart(currentUser);
            return HttpResult.success("购物车已清空");
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "清空购物车失败: " + e.getMessage());
        }
    }

    // 7. 获取购物车摘要信息
    @GetMapping("/carts/summary")
    @Operation(summary = "获取购物车摘要", description = "获取购物车中商品总数、总金额等信息")
    public HttpResult<CartService.CartSummary> getCartSummary() {
        try {
            // 获取当前用户
            User currentUser = userService.getUserWithAuthorities()
                    .orElseThrow(() -> new RuntimeException("用户未登录"));
            
            // 通过服务层获取购物车摘要
            CartService.CartSummary summary = cartService.getCartSummary(currentUser);
            return HttpResult.success(summary);
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "获取购物车摘要失败: " + e.getMessage());
        }
    }
    
    // 添加到 CartController 中
    @GetMapping(value = "/carts", params = "businessId") // 通过 params 区分同一个URL的不同功能
    @Operation(summary = "获取指定店铺的购物车商品", description = "获取当前用户购物车中属于某店铺的所有商品")
    public HttpResult<List<Cart>> getCartItemsByBusiness(@RequestParam Long businessId) {
        try {
            User currentUser = userService.getUserWithAuthorities()
                    .orElseThrow(() -> new RuntimeException("用户未登录"));
            
            List<Cart> cartItems = cartService.getCartItemsByBusinessId(currentUser, businessId);
            return HttpResult.success(cartItems);
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "获取购物车失败: " + e.getMessage());
        }
    }
}
